package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.RongXinYongCaiApiBUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 融信用采 APIB回调
 */
@Service
public class RongXinYongCaiApiBPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    DataMatchOrderItemMapper dataMatchOrderItemMapper;

    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();
        String channelId = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();

        // 格式化当前时间
        String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));


        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("phoneMd5",mobileMd5);
        bizMap.put("userName",memberSourceInfo.getRealname());
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("sex",memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("zhimaCredit", RongXinYongCaiApiBUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("fund", RongXinYongCaiApiBUtil.getFund(memberSourceInfo.getGjj()));
        bizMap.put("has", RongXinYongCaiApiBUtil.getShebao(memberSourceInfo.getShebao()));
        bizMap.put("bdStatus", RongXinYongCaiApiBUtil.getBaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("houseProperty", RongXinYongCaiApiBUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carProperty", RongXinYongCaiApiBUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("loanAmount", RongXinYongCaiApiBUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("professional", RongXinYongCaiApiBUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("registerIp", RongXinYongCaiApiBUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("platform", "Android");


        //加密
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId",channelId);
        paramMap.put("content",encrypt);
        paramMap.put("date",formattedTime);
        paramMap.put("reqNo", UUID.randomUUID().toString());

        log.info("【融信用采APIB】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【融信用采APIB】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            String orderId = data.getString("orderId");
            String redirectUrl = data.getString("url");

            pushApiResult.setPushSuccess(true);
            pushApiResult.setApproveUrl(redirectUrl);
            pushApiResult.setOutOrderNo(orderId);

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderId",orderId);
            pushApiResult.setExtJson(jsonObject);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        String channelId = pushApiKeyParam.getApiCode();
        String apiSecret = pushApiKeyParam.getApiSecret();
        String mobile = memberSourceInfo.getMobile();

        // 格式化当前时间
        String formattedTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("orderId",outOrderNo);
        bizMap.put("phone",mobile);
        bizMap.put("userName",memberSourceInfo.getRealname());
        bizMap.put("age",memberSourceInfo.getAge());
        bizMap.put("sex",memberSourceInfo.getSex() == 1 ? 1 : 0);
        bizMap.put("city",memberSourceInfo.getCity());
        bizMap.put("cityCode",memberSourceInfo.getCityCode());
        bizMap.put("zhimaCredit", RongXinYongCaiApiBUtil.getZhima(memberSourceInfo.getZhima()));
        bizMap.put("fund", RongXinYongCaiApiBUtil.getFund(memberSourceInfo.getGjj()));
        bizMap.put("has", RongXinYongCaiApiBUtil.getShebao(memberSourceInfo.getShebao()));
        bizMap.put("bdStatus", RongXinYongCaiApiBUtil.getBaodan(memberSourceInfo.getBaoxian()));
        bizMap.put("houseProperty", RongXinYongCaiApiBUtil.getHouse(memberSourceInfo.getHouse()));
        bizMap.put("carProperty", RongXinYongCaiApiBUtil.getCar(memberSourceInfo.getCar()));
        bizMap.put("loanAmount", RongXinYongCaiApiBUtil.getloan(memberSourceInfo.getLoanAmount()));
        bizMap.put("professional", RongXinYongCaiApiBUtil.getJob(memberSourceInfo.getGongzuo()));
        bizMap.put("registerIp", RongXinYongCaiApiBUtil.getReqIp(memberSourceInfo.getReqIp()));
        bizMap.put("platform", "Android");

        DataMatchOrderItem dataMatchOrderItem = dataMatchOrderItemMapper.selectDataMatchOrderItemStatus(orderNo, String.valueOf(pushApiKeyParam.getInfoId()));
        String orderId = String.valueOf(dataMatchOrderItem.getOrderId());
        String orderItemId = String.valueOf(dataMatchOrderItem.getId());
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        bizMap.put("protocolUrl", protocolUrl);

        //加密
        String encrypt = SecureUtil.aes(apiSecret.getBytes()).encryptBase64(JSON.toJSONString(bizMap));


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("channelId",channelId);
        paramMap.put("content",encrypt);
        paramMap.put("date",formattedTime);
        paramMap.put("reqNo", UUID.randomUUID().toString());

        log.info("【融信用采APIB】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【融信用采APIB】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject1 = JSON.parseObject(paramContent);
        String orderId = jsonObject1.getString("orderId");
        noticeParamDTO.setOutOrderNo(orderId);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderId));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",200);
        jsonObject.put("msg","成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

}
